package it.unina.lab.anm.activity;


import it.unina.lab.anm.Costants;
import it.unina.lab.anm.R;
import it.unina.lab.anm.dao.DatabaseService;
import it.unina.lab.anm.models.Fermata;
import it.unina.lab.anm.ui.UIUtils;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class FavouriteStopsListActivity extends ListActivity {

	private final static int CONTEXT_MENU_DELETE_FAVOURITE_STOP = 0;
	private final static int CONTEXT_MENU_VIEW_FAVOURITE_STOP = 1;
	private final static int CONTEXT_MENU_SETALIAS_FAVOURITE_STOP = 2;
	
	private ListView mListView;
	private TextView text_no_stops;
	private StopsListAdapter mListAdapter;
	private List<Fermata> favouriteStopsList = new ArrayList<Fermata>();
	private DatabaseService mDB;

	
	/**
	 * On Create
	 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	  
	
		setContentView(R.layout.favourite_stops_list);
		((TextView) findViewById(R.id.title_text)).setText(this.getResources().getString(R.string.btn_starred));
		mListView = (ListView) getListView();
		text_no_stops = (TextView) findViewById(R.id.favourite_stop_view_textNoStops);
		
		
		// Home title button
		findViewById(R.id.title_btn_home).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    	UIUtils.goHome(FavouriteStopsListActivity.this);
		    }
		});	

		// Search title button
		findViewById(R.id.title_btn_search).setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    	UIUtils.goSearch(FavouriteStopsListActivity.this);
		    }
		});	
		
		
		mDB = DatabaseService.getDatabaseServiceIstance(this);
		displayStops();
	}

	
	/**
	 * Close the DB connection if this activity finishes
	 */
    @Override
    protected void onDestroy() {
        super.onDestroy();
    	//mDB.close();
    }
	
    
	
	
	/**
	 * Carica la lista dal DB e Display the list of stops
	 */
	public void displayStops() {
		
		favouriteStopsList = mDB.getFermatePreferite();
		if(favouriteStopsList.size() > 0)
			text_no_stops.setVisibility(View.GONE);
		else
			text_no_stops.setVisibility(View.VISIBLE);
		
		mListView.setOnItemClickListener(mListView_OnItemClickListener);		
		mListView.setOnCreateContextMenuListener(mListView_OnCreateContextMenuListener);
		mListAdapter = new StopsListAdapter();
		setListAdapter(mListAdapter);
	}
	
	
	
	
	
	/**
	 * Cancella la fermata selezionata
	 * @param stop
	 */
	private void deleteStop(Fermata stop){
		if(mDB.delete_fermata_preferita(stop.getNumeroPalina()))
			UIUtils.popToastLong(this, "Fermata preferita eliminata!");
		
		//Refresho la view
		displayStops();
	} 
	
	
	
	
	/**
	 * Visualizza la fermata selezionata
	 * @param stop
	 */
	private void viewStop(Fermata stop){
		Intent intent = new Intent(FavouriteStopsListActivity.this, StopDetailsActivity.class);
    	intent.putExtra(Costants.INTENT_SHOW_DETAIL_PALINA_NUMEROPAL_DATAKEY, stop.getNumeroPalina());
    	startActivity(intent);	
	} 
	
	
	/**
	 * Modifica l'alias della fermata
	 * @param stop
	 */
	private void nameStop(final Fermata stop) {
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setTitle(this.getResources().getString(R.string.label_setAlias_favourite_stop));
		alert.setIcon(R.drawable.star_on);

		// Set the initial stop name in the text field
		input.setText(stop.getAlias());
		final CharSequence message = this.getResources().getString(R.string.label_setAlias_dialog_message_favourite_stop) 
									 + " " + stop;
		alert.setMessage(message);
		
		// Save the new stop name
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String customName = input.getText().toString().trim();
				stop.setAlias(customName);
				
				//aggiorno il database e refresho la view
				if(mDB.update_alias_fermata_preferita(stop)){
					UIUtils.popToastLong(FavouriteStopsListActivity.this, "Alias modificato!");
					displayStops();
				}	
			}
		});

		
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});
		alert.show();
		
	}
	
	
	
	
	
	
	/**
	 * List item click action
	 */
	private OnItemClickListener mListView_OnItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> adapterView, View row, int position, long id) {
			viewStop((Fermata)favouriteStopsList.get(position));
		}
    };

    
    
    
    
    
    /**
     * Create the context menu
     */
 	private OnCreateContextMenuListener mListView_OnCreateContextMenuListener = new OnCreateContextMenuListener() {
		public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
			AdapterView.AdapterContextMenuInfo info;
			try {
			    info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			} catch (ClassCastException e) {
			    return;
			}

			Fermata thisStop = (Fermata)favouriteStopsList.get(info.position);
			menu.setHeaderIcon(R.drawable.star_on);
			menu.setHeaderTitle(v.getResources().getString(R.string.label_stop_number)
								+ thisStop.getNumeroPalina());
			menu.add(0, CONTEXT_MENU_DELETE_FAVOURITE_STOP, 0, v.getResources().getString(R.string.label_delete_favourite_stop));
			menu.add(0, CONTEXT_MENU_VIEW_FAVOURITE_STOP, 0, v.getResources().getString(R.string.label_view_favourite_stop));
			menu.add(0, CONTEXT_MENU_SETALIAS_FAVOURITE_STOP, 0, v.getResources().getString(R.string.label_setAlias_favourite_stop));
		}
    }; 
    
    
    
    
    
    
    /**
     * Context menu actions
     */
    
    public boolean onContextItemSelected (MenuItem item){
    	try {
    		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        	Fermata thisStop = (Fermata)favouriteStopsList.get(info.position);
        	
        	switch (item.getItemId()) {
    			case CONTEXT_MENU_DELETE_FAVOURITE_STOP:
    				deleteStop(thisStop);
    				return true;
    				
    			case CONTEXT_MENU_VIEW_FAVOURITE_STOP:
    				viewStop(thisStop);
    				return true;
    				
    			case CONTEXT_MENU_SETALIAS_FAVOURITE_STOP:
    				nameStop(thisStop);
    				return true;	
    			
        	}
    	} catch (ClassCastException e) {}
    	    	
		return super.onContextItemSelected(item);
    } 
     
    
    
    /**
     * Stops list adapter
     * @author andy
     *
     */
	private class StopsListAdapter extends BaseAdapter {

		public int getCount() {
			return favouriteStopsList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View pv;
            if(convertView == null) {
    			LayoutInflater inflater = getLayoutInflater();
    			pv = inflater.inflate(R.layout.favourite_stops_list_row, parent, false);
            }
            else {
                pv = convertView;
            }
			
            Fermata thisStop = (Fermata) favouriteStopsList.get(position);
			
			((TextView) pv.findViewById(R.id.favouriteView_stopNameTextView)).setText(thisStop.getAlias());
			((TextView) pv.findViewById(R.id.favouriteView_stopAddressTextView)).setText(thisStop.getIndirizzo());
			((TextView) pv.findViewById(R.id.favouriteView_stopNumber)).setText(pv.getResources().getString(R.string.label_stop_number)
										+ thisStop.getNumeroPalina());
			((TextView) pv.findViewById(R.id.favouriteView_stopLineeTransitoTextView)).setText(thisStop.getBuses().toString()); 

			return pv;
		}
			
	}



	

	@Override
	protected void onRestart() {
		displayStops();
		super.onRestart();
	}


	@Override
	protected void onResume() {
		displayStops();
		super.onResume();
	}



	
	
	
	
	
}